using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml;

namespace InfiniTec.DirectoryServices
{   
    /// <summary>
    /// The searchtoken encapsulates information about a search operation, and can be used
    /// to recreate a <see cref="Searcher"/> instance to continue a previously started 
    /// search.
    /// </summary>
    [Serializable]
    public class SearchToken: IXmlSerializable
    {
        private int _PageSize;
        private byte[] _Token;

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchToken"/> class.
        /// </summary>
        public SearchToken()
        {
        }

        internal SearchToken(int pageSize, byte[] token): this(pageSize)
        {
            Token = token;
        }

        internal SearchToken(int pageSize)
        {
            PageSize = pageSize;
        }

        internal byte[] Token
        {
            [DebuggerStepThrough]
            get { return _Token; }
            [DebuggerStepThrough]
            set { _Token = value; }
        }

        /// <summary>
        /// Gets or sets the size of the page.
        /// </summary>
        /// <value>The size of the page.</value>
        public int PageSize
        {
            [DebuggerStepThrough]
            get { return _PageSize; }
            [DebuggerStepThrough]
            set { _PageSize = value; }        
        }

        internal bool IsValid()
        {
            if (PageSize == 0) return false;
            if (Token == null || Token.Length == 0) return false;

            return true;
        }

        #region IXmlSerializable Members

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            reader.MoveToAttribute("pageSize");
            _PageSize = reader.ReadContentAsInt();

            reader.MoveToContent();
            _Token = Convert.FromBase64String(reader.ReadContentAsString());
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("pageSize", PageSize.ToString());
            writer.WriteBase64(Token, 0, Token.Length);            
        }

        #endregion

    }
}
